﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using Utils;

namespace RhotCMS.Models
{
    /// <summary>
    /// Use this class to work with Settings
    /// </summary>
    public class CMSSettingsRepository
    {
        /// <summary>
        /// Saves single setting value by key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="newValue"></param>
        public static void SetAppSingleSetting(string key, string newValue)
        {
            var configuration = WebConfigurationManager.OpenWebConfiguration("~");
            var section = (AppSettingsSection)configuration.GetSection("appSettings");
            section.Settings[key].Value = newValue;
            configuration.Save();           
        }

        /// <summary>
        /// Returns setting value by key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSingleAppSetting(string key)
        {
            var configuration = WebConfigurationManager.OpenWebConfiguration("~");
            var section = (AppSettingsSection)configuration.GetSection("appSettings");
            return section.Settings[key].Value;            
        }

        /// <summary>
        /// Returns all app settings
        /// </summary>
        /// <returns></returns>
        public static SettingsModel GetAppSettings()
        {
            SettingsModel settingsModel = new SettingsModel();
            settingsModel.SiteName = GetSingleAppSetting("SiteName");
            settingsModel.IsMultiLanguage = Convert.ToBoolean(GetSingleAppSetting("IsMultiLanguage"));
            return settingsModel;
        }

        /// <summary>
        /// Saves settings model
        /// </summary>
        /// <param name="model"></param>
        public static void SetAppSettings(SettingsModel model)
        {
            SetAppSingleSetting("SiteName", model.SiteName);
            SetAppSingleSetting("IsMultiLanguage", model.IsMultiLanguage.ToString());
        }
    }
}